package cn.gx.kevin.common.utils;

import cn.gx.kevin.common.thread.*;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;

/**
 * 拦截请求，清理线程变量
 * 如果有需要，注入权限拦截实现，全局操作记录
 * ***/
public class RequestInterceptor implements HandlerInterceptor {

    private static final Log LOGGER = LogFactory.getLog(HandlerInterceptor.class);

    LinkedList<IRequestInterceptor> interceptors = new LinkedList<>();

    public RequestInterceptor(){}
    public RequestInterceptor(IRequestInterceptor requestInterceptor){
        interceptors.add(requestInterceptor);
    }

    public void setRequestInterceptor(IRequestInterceptor requestInterceptor) {
        interceptors.add(requestInterceptor);
    }

    /***
     * 在controller执行后执行
     **/
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        if(interceptors.size() > 0){
            try{
                for(IRequestInterceptor interceptor : interceptors){
                    interceptor.afterExecute(arg0,arg1,arg3);
                }
            }catch (Exception x){
                LOGGER.error("",x);
            }
        }
        ThreadHolderClearer.clear();
    }

    /*****
     * 在controller执行前
     ******/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        ThreadHolderClearer.clear();
        boolean isPast = true;
        if(interceptors.size() > 0){
            for(IRequestInterceptor interceptor : interceptors){
                isPast = interceptor.beforeExecute(request,response,arg2);
                if(!isPast){
                    break;
                }
            }
        }
        if(isPast){
            ResponseThreadHolder.setResponse(response);
            RequestThreadHolder.setRequest(request);
        }
        return isPast;
    }
}